package cn.tedu.mintmall.service.impl;

import cn.tedu.mintmall.constant.RewardState;
import cn.tedu.mintmall.dto.RewardAddNewDTO;
import cn.tedu.mintmall.entity.Reward;
import cn.tedu.mintmall.exception.MintmallServiceException;
import cn.tedu.mintmall.mapper.RewardMapper;
import cn.tedu.mintmall.query.RewardQuery;
import cn.tedu.mintmall.restful.JsonPage;
import cn.tedu.mintmall.restful.ResponseCode;
import cn.tedu.mintmall.service.IRewardService;
import cn.tedu.mintmall.vo.RewardVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class RewardImpl implements IRewardService {

    @Autowired
    private RewardMapper rewardMapper;

    // 新增打赏
    @Override
    public void AddReward(RewardAddNewDTO rewardAddNewDTO) {

        Reward reward = new Reward();
        BeanUtils.copyProperties(rewardAddNewDTO,reward);
        if (reward.getAmount()<50){
            reward.setState(RewardState.JUNIOR);
        } else if(reward.getAmount()>200){
            reward.setState(RewardState.SENIOR);
        } else {
            reward.setState(RewardState.INTERMEDIATE);
        }
        LocalDateTime now = LocalDateTime.now();
        reward.setDate(now);
        reward.setGmtCreate(now);
        reward.setGmtModified(now);
        log.info("新增奖赏成功:{}",reward); // useGeneratedKeys未执行, 无id
        int rows = rewardMapper.insertReward(reward);
        if (rows == 0){
            throw new MintmallServiceException(ResponseCode.INTERNAL_SERVER_ERROR, "服务器忙, 请稍后再试!");
        }
        log.info("新增奖赏成功:{}",reward);// useGeneratedKeys执行, 有id

    }

    // 按打赏时间分页展示所有打赏信息
    @Override
    public JsonPage<RewardVO> findAllRewards(Integer page, Integer pageSize) {

        PageHelper.startPage(page,pageSize);
        List<RewardVO> list = rewardMapper.findAllRewards();
        if (list.size() == 0){
            throw new MintmallServiceException(ResponseCode.INTERNAL_SERVER_ERROR, "未查到打赏信息, 请稍后再试!");
        }
        return JsonPage.restPage(new PageInfo<>(list));

    }

    // 获取打赏金额前3名的信息按金额降序
    @Override
    public List<RewardVO> listByAmountTopThreeRewards() {
        List<RewardVO> list = rewardMapper.listByAmountTopThreeRewards();
        if (list.size() == 0){
            throw new MintmallServiceException(ResponseCode.INTERNAL_SERVER_ERROR, "未查到打赏信息, 请稍后再试!");
        }
        return list;
    }

    // 按条件搜索打赏信息
    @Override
    public List<RewardVO> listByCustomConditions(RewardQuery rewardQuery) {
        List<RewardVO> list = rewardMapper.listByCustomConditions(rewardQuery);
        if (list.size() == 0){
            throw new MintmallServiceException(ResponseCode.BAD_REQUEST, "未查到打赏信息, 请稍后再试或更换查询条件!");
        }
        return list;
    }

}
